# -*- coding: utf-8 -*-

import re
import string
import routines as r


def cleanup_address(text, debug=False):
    ''' cleanup of address
    '''
    t = r.remove_eol(text)
    t = t.strip()
    # remove multiple spaces, comas
    t = re.sub('[,]', '', t)
    t = re.sub(' {2,}', ' ', t)
    t = r.ascii_upper(t)
    
    if debug and t == '':
        ef = open('err_clean_address.log', 'a')
        ef.write('Error\tEmpty address.\t' + text + '\n')
        ef.close()
        return t
    else:
        return t


def cleanup_email(text, debug=False):
    ''' cleanup of email data
    '''
    t = r.remove_eol(text)
    t = t.strip()
    # remove multiple spaces, comas
    t = re.sub('[ ,]', '', t)
    t = r.ascii_upper(t)

    if debug and string.find(t, '@') == -1:
        ef = open('err_clean_email.log', 'a')
        ef.write('Error\tMissing @.\t' + text + '\n')
        ef.close()
        return t
    else:
        return t

if 0:
    print cleanup_email('dsada@daasds.cz')
    print cleanup_email('dsada_daasds.cz')


def cleanup_sur_name(text, debug=False):
    ''' cleanup of name OR surname
    '''
    t = r.remove_eol(text)
    t = t.strip()
    # remove multiple spaces, comas
    t = re.sub('[ ,]', '', t)
    t = r.ascii_upper(t)
    
    '''
    if debug and string.find(t, '@') == -1:
        ef = open('clean_sur_name.log', 'a')
        ef.write('error:missing @ >> ' + text + '\n')
        ef.close()
        return t
    else:
        return t
    '''
    return t


def cleanup_pid_czsk(text, debug=False):
    ''' cleanup of personal id, czech/slovak data
    '''
    t = r.remove_eol(text)
    t = t.strip()
    # remove multiple spaces, comas
    t = re.sub('[ ,/]', '', t)
    t = r.ascii_upper(t)
    
    '''
    if debug and string.find(t, '@') == -1:
        ef = open('clean_pid_czsk.log', 'a')
        ef.write('error:missing @ >> ' + text + '\n')
        ef.close()
        return t
    else:
        return t
    '''
    return t


def cleanup_phone_czsk(text, debug=False, country='cz'):
    ''' cleanup of phone number, czech/slovak data
    '''
    t = r.remove_eol(text)
    t = t.strip()
    # remove multiple spaces, comas
    t = re.sub('[ ,]', '', t)
    t = r.ascii_upper(t)

    if country == 'cz':
        if re.search('^\+42', t):
            pass # desired format
        elif re.search('^00', t):
            t = '+' + t[2:]
        elif re.search('^420', t):
            t = '+' + t[3:]
        elif re.search('^421', t):
            t = '+' + t[3:]
        elif re.search('^\+', t):
            pass # desired format
        else:
            t = '+420' + t
    
    if debug and len(t) < 13:
        ef = open('err_clean_phone_czsk.log', 'a')
        ef.write('Error\tLess than 13 characters.\t' + text + '\n')
        ef.close()
        return t
    else:
        return t
